package com.lighting.smssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.qcloudsms.httpclient.HTTPException;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.mapper.CompanyMapper;
import com.lighting.smssystem.mapper.TemplateMapper;
import com.lighting.smssystem.mapper.UserMapper;
import com.lighting.smssystem.model.Company;
import com.lighting.smssystem.model.Template;
import com.lighting.smssystem.model.User;
import com.lighting.smssystem.model.bo.CompanyList;
import com.lighting.smssystem.model.vo.AddCompanies;
import com.lighting.smssystem.model.vo.CompanyFilter;
import com.lighting.smssystem.model.vo.CompanyFilterNew;
import com.lighting.smssystem.model.vo.CompanyForm;
import com.lighting.smssystem.service.ICompanyService;
import com.lighting.smssystem.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author leemaster
 * @Title: CompanyService
 * @Package com.lighting.smssystem.service.impl
 * @Description:
 * @date 2019-06-0200:00
 */
@Service
@Slf4j
public class CompanyService implements ICompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private TemplateMapper templateMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ISmsService smsService;


    @Override
    public CompanyList queryCompanyList(CompanyFilterNew filter) {

        IPage<Company> page = companyMapper.selectPage(
                new Page<>(filter.getPageNum(),filter.getPageSize()),
                Wrappers.<Company>query()
                        .like(!StringUtils.isEmpty(filter.getCityKey()),"company_city",filter.getCityKey())
                        .or()
                        .like(!StringUtils.isEmpty(filter.getLegalKey()),"company_legal",filter.getLegalKey())
                        .or()
                        .like(!StringUtils.isEmpty(filter.getProvinceKey()),"company_province",filter.getProvinceKey())
                        .or()
                        .like(!StringUtils.isEmpty(filter.getRangeKey()),"company_range",filter.getRangeKey())
                .orderByDesc("update_at","company_legal")

        );
        Long total = page.getTotal();
        return new CompanyList(total, page.getRecords(), (long) filter.getPageNum(), (long) filter.getPageSize(),
                (long) Math.ceil((total / filter.getPageSize())));
    }

    @Override
    public CompanyList queryCompanyListOld(CompanyFilter filter) {
        IPage<Company> page = companyMapper.selectPage(
                new Page<>(filter.getPageNum(), filter.getPageSize()),
                Wrappers.<Company>query()
                        .like(true, "company_name", filter.getKeyword())
                        .or()
                        .like(true, "company_type", filter.getKeyword())
                        .or()
                        .like(true, "company_address", filter.getKeyword())
                        .or()
                        .like(true, "company_website", filter.getKeyword())
                        .or()
                        .like(true, "company_mail", filter.getKeyword())
                        .or()
                        .like(true, "company_city", filter.getKeyword())
                        .or()
                        .like(true, "company_legal", filter.getKeyword())
                        .or()
                        .like(true, "company_province", filter.getKeyword())
                        .or()
                        .like(true, "company_range", filter.getKeyword())
                        .orderByDesc("update_at", "company_legal")

        );
        Long total = page.getTotal();
        return new CompanyList(total, page.getRecords(), (long) filter.getPageNum(), (long) filter.getPageSize(),
                (long) Math.ceil((total / filter.getPageSize())));
    }

    public Company company(Long id) {
        return companyMapper.selectById(id);
    }

    @Override
    public int deleteCompanies(List<Long> id) {
        return companyMapper.deleteBatchIds(id);
    }

    @Override
    @Transactional
    public int addCompanies(AddCompanies addCompanies) {

        List<Company> companies = addCompanies.getCompanies()
                .stream().map(Company::new).collect(Collectors.toList());

        Template template = templateMapper.selectOne(
                Wrappers.<Template>query().eq("template_ext_id",addCompanies.getTemplate())
        );

        List<User> users = userMapper.selectList(
                Wrappers.<User>query().eq("user_role", UserRole.VIP)
        );

        List<String> phones = users.stream().map(User::getUserPhone).collect(Collectors.toList());

        try {
            companies.forEach(company -> companyMapper.insert(company));
            String[] data = new String[phones.size()];
            phones.toArray(data);
            smsService.sendMultiSms(template,new HashMap<String,String>(), data);

            return companies.size();
        } catch (HTTPException | IOException e) {
           log.error("[Send message failed, with the phone {}]",phones);
           throw new RuntimeException("SendFailed");
        }

    }

    @Override
    @Transactional
    public int updateCompanies(List<CompanyForm> companies) {

        List<Company> companies1 = companies.stream().map(Company::generateCompany).collect(Collectors.toList());

        companies1.forEach(company -> companyMapper.updateById(company));

        return companies1.size();
    }
}
